<template>
  <el-dialog
    :visible="visible"
    title="添加角色"
    class="dialog"
    width="400px"
    @close="cancel"
  >
    <el-form ref="form" :model="form" :rules="rules" label-width="auto">
      <el-form-item prop="name" label="角色名称">
        <el-input v-model="form.name" placeholder="请输入角色名称" />
      </el-form-item>
      <el-form-item prop="state" label="启用">
        <el-switch
          v-model="form.state"
          active-color="#13ce66"
          inactive-color="#ff4949"
          active-value="1"
          inactive-value="0"
        />
      </el-form-item>
      <el-form-item prop="description" label="角色描述">
        <el-input
          v-model="form.description"
          placeholder=" 请输入角色描述"
          :rows="4"
          class="textarea"
          type="textarea"
        />
      </el-form-item>
      <el-form-item class="form-butBox">
        <div class="butBox">
          <el-button
            round
            size="medium"
            type="warning"
            @click="confirm"
          >确定</el-button>
          <el-button
            round
            size="medium"
            type="info"
            @click="cancel"
          >取消</el-button>
        </div>
      </el-form-item>
    </el-form>
  </el-dialog>
</template>

<script>
import { postRoleAPI } from '@/api/role'
export default {
  props: {
    // props获取父组件传递的visible
    visible: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      // 校验规则
      rules: {
        name: [{ required: true, message: '请输入角色名称', trigger: 'blur' }],
        state: [{ required: true, message: '...', trigger: 'blur' }],
        description: [
          { required: true, message: '请输入角色描述', trigger: 'blur' }
        ]
      },
      // 表单数据
      form: {
        name: '',
        description: '',
        state: ''
      }
    }
  },
  watch: {
    // 侦听弹框的visible
    async visible(newValue, oldValue) {
      !newValue && await this.$refs.form.resetFields()
      !newValue && this.$emit('getTableList')
    }
  },
  created() {},
  methods: {
    // dialog确认
    async confirm() {
      // 校验表单
      await this.$refs.form.validate()
      // 发送请求
      await postRoleAPI(this.form)
      // 响应提示
      // 清空表单
      // 刷新数据
      // 关闭弹框
      this.$emit('update:visible', false)
    },
    // // dialog取消
    cancel() {
      this.$emit('update:visible', false)
    }
  }
}
</script>

<style>
</style>
